<template>
  <el-dialog v-model="dialog.showDialog" :append-to-body="false" :close-on-click-modal="false"
             :destroy-on-close="false" :loading="dialog.loading" :submit-icon="dialog.submitIcon"
             :submit-txt="dialog.submitTxt"
             :title="dialog.title" class="avue-dialog avue-crud__dialog" draggable width="1200" @close="cancleDialog">
    <avue-form ref="topFormRef" v-model="topForm" :option="topOption"></avue-form>

    <basic-crud ref="bottomCrudRef" v-model="bottomForm"
                :apiListParams="listPatrams" :autoLoad="false"
                :defaultListParams="{}"
                :option="option"
                :permission="getPermission"
                apiGetListMethod="post"
                apiGetListUrl="/mpm/processController/listHasChildren"
                selectType="multiple"
                @row-update="rowUpdate"
                @selection-change="handleChangeSelect">
      <template #menu-left>
        <el-button icon="user" plain type="primary" @click="batchSetWorkerName">批量设置操作员</el-button>
        <el-button icon="user" plain type="primary" @click="batchSetCheckerName">批量设置检验员</el-button>
      </template>
    </basic-crud>
    <template #footer>
      <div class="dialog-footer avue-dialog__footer footer_box">
        <el-button
            :icon="dialog.submitIcon"
            type="primary"
            @click="submitDialog"
        >{{ dialog.submitTxt }}
        </el-button>
        <el-button
            icon="el-icon-circle-close"
            @click="cancleDialog"
        > 取消
        </el-button
        >
      </div>
    </template>
    <BasicCrudUserRefer ref="crudReferRef" v-model="UserVisible"
                        @submit="handleSetWorkerNameSubmit"></BasicCrudUserRefer>
  </el-dialog>
</template>

<script setup>
import {computed, defineExpose, nextTick} from 'vue';
import {verifyNotNull, verifyNull} from "../../../utils/validate";
import {editAllotSchema, cloneSchema, addAllotSchema, getObject} from '../../../apis/generate/treatDispatching'

const emits = defineEmits(['refresh-parent'])
const dialog = ref({
  showDialog: false,
  title: "新增",
  submitTxt: "保存",
  submitIcon: "el-icon-circle-check",
  loading: false,
});

const topFormRef = ref(null);
const topForm = ref({
  workOrderId: "",
  id: '',
  name: "",
  specificationId: "",
  specificationName: ''
});
const bottomCrudRef = ref(null);
const specId = ref('');
const bottomForm = ref({});

const listPatrams = computed(() => ({
  specificationId: specId.value
}))

const topOption = ref({
  menuBtn: false,
  submitBtn: false,
  emptyBtn: false,
  column: [
    {
      prop: "specificationName",
      label: "规程版本",
      component: 'BasicCrudTableSelect',
      comProps: {
        saveFieldMap: {specificationName: 'name', specificationId: 'specificationId'},
        comType: 'form',
      },
      crudProps: {
        fastSearch: {name: '规程编号、规程名称、产品型号,产品名称', fastColumn: 'code,name,productCode,productName'},
        apiReferUrl: '/mpm/processSpecificationController/getSpecList',
        option: {
          header: true,
          addBtn: false,
          menu: false,
          column: [
            {prop: 'code', label: '规程编号', search: true},
            {prop: 'name', label: '规程名称', search: true},
            {prop: 'rev', label: '版本', search: true},
            {prop: 'productCode', label: '产品型号', search: true},
            {prop: 'productName', label: '产品名称', search: true},
          ]
        }
      },
      curForm: topForm,
      change: (newV) => {
        topForm.value = newV;
        topFormRef.value?.clearValidate();
        if (newV) {
          specId.value = newV.id
        }
      },
    },
    {
      prop: "name",
      fieldId: "name",
      label: "方案名称",
      type: "input",
      rules: [{required: true, message: "请输入方案名称", trigger: "blur"}],
      col: 12,
    },
  ]
});
// 打开新增编辑对话框
const openDialog = (row) => {
  dialog.value.showDialog = true;
  if (row && (row.edit || row.clone)) {
    if (row.clone) {
      clone.value = true;
      dialog.value.title = '克隆';
    } else {
      edit.value = true;
      dialog.value.title = '编辑';
    }
    parentRow.value = row;
    if (row.id) {
      getObject({id: row.id}).then(res => {
        if (res.success) {
          let obj = res.obj;
          topForm.value.id = obj.id;
          topForm.value.name = obj.name;
          topForm.value.specificationId = obj.specificationId;
          topForm.value.specificationName = obj.specificationName;
          bottomCrudRef.value.tableData = Array.isArray(obj.itemList)
              ? obj.itemList
              : [];
          nextTick(() => {
            bottomCrudRef.value.doLayout();
          });
        } else {
          ElMessage.error(res.msg);
        }
      });
    } else {
      ElMessage.error("未能获取到数据");
      dialog.value.showDialog = false;
      return false;
    }
  }
  ;
};
const cancleDialog = () => {
  topFormRef.value?.resetFields();
  bottomCrudRef.value.tableData = [];
  dialog.value.showDialog = false;
  edit.value = false;
  clone.value = false;
};
const getAllTableData = (tableData, processData) => {
  if (!Array.isArray(processData)) return;
  processData.forEach((item) => {
    tableData.push(item);
    if (item.children && item.children.length > 0) {
      getAllTableData(tableData, item.children);
    }
  });
};
const getPermission = (key, row) => {
  if (key === 'editBtn' && row.parentId === specId.value) {
    return false;
  }
  return true;
};

const option = ref({
  highlightCurrentRow: true,
  size: 'small',
  height: 'auto',
  addBtn: false,
  viewBtn: false,
  delBtn: false,
  rowKey: "id",
  rowParentKey: "parentId",
  isTableTree: true,
  calcHeight: 200,
  menuWidth: 120,
  column: [
    {
      label: "工步号",
      prop: "code",
      display: false,
    },
    {
      label: "工步名称",
      prop: "name",
      display: false,
    },
    {
      label: "操作者",
      prop: "workerName",
      width: 200,
      labelWidth: 140,
      click: () => {
        selectUserType.value = 'workerNameForm';
        UserVisible.value = true;
      },
    },
    {
      label: "检验员",
      prop: "checkerName",
      width: 200,
      labelWidth: 140,
      click: () => {
        selectUserType.value = 'checkerNameForm';
        UserVisible.value = true;
      },
    },
    {
      label: "是否固定军检",
      prop: "fixedArmyFlag",
      width: 100,
      type: "select",
      labelWidth: 140,
      dicData: [
        {
          label: "是",
          value: "true",
        },
        {
          label: "否",
          value: "false",
        },
      ],
      formatter: function (d) {
        if (d.fixedArmyFlag == "true") {
          return "是";
        } else if (d.children && d.children.length > 0) {
          return "";
        } else if (d.fixedArmyFlag == "false") {
          return "否";
        } else {
          return "";
        }
      },
    },
  ],
});

const selectList = ref([]);
const selectUserType = ref('');
const UserVisible = ref(false);
const handleChangeSelect = (row) => {
  selectList.value = row;
};
const batchSetWorkerName = () => {
  if (selectList.value.length <= 0) {
    ElMessage.error("请选择至少一条需要设置人员的数据！");
    return false;
  }
  selectUserType.value = "workBatch";
  UserVisible.value = true;
  // this.$refs.userDialog.show({multi:true,aptitude:true});
};

const batchSetCheckerName = () => {
  if (selectList.value.length <= 0) {
    ElMessage.error("请选择至少一条需要设置人员的数据！");
    return false;
  }
  selectUserType.value = "checker";
  UserVisible.value = true;
};
const crudReferRef = ref(null)

// 操作员回填
const handleSetWorkerNameSubmit = (selections) => {
  console.log(selections)
  let tempData = {};
  if (selectUserType.value === 'workerNameForm') {
    bottomForm.value.workerName = selections.map(val => val.name).join(",");
    bottomForm.value.workerCode = selections.map(val => val.code).join(",");
    bottomForm.value.worker = selections.map(val => val.id).join(",");
    return crudReferRef.value.handlerCancel();
  }
  if (selectUserType.value === 'checkerNameForm') {
    bottomForm.value.checkerName = selections[0].name;
    bottomForm.value.checkerCode = selections[0].code;
    bottomForm.value.checker = selections[0].id;
    return crudReferRef.value.handlerCancel();
  }
  if (selectUserType.value == 'workBatch') {
    selectList.value.forEach((item) => {
      if (!item.children || item.children.length == 0) {
        item.worker = selections.map(val => val.id).join(",");
        item.workerCode = selections.map(val => val.code).join(",");
        item.workerName = selections.map(val => val.name).join(",");
        tempData[item.id] = item;
      }
    });
  } else {
    //检验员
    selectList.value.forEach((item) => {
      if (!item.children || item.children.length == 0) {
        item.checker = selections[0].id;
        item.checkerCode = selections[0].code;
        item.checkerName = selections[0].name;
        tempData[item.id] = item;
      }
    });
  }
  let data = bottomCrudRef.value.tableData;

  let tableData = [];
  data.forEach((item) => {
    if (item.id in tempData) {
      item = tempData[item.id];
    }
    tableData.push(item);
  });
  data = tableData;
  crudReferRef.value.handlerCancel();
};

const edit = ref(false);
const clone = ref(false);
const parentRow = ref({});
const currentTableData = computed(() => {
  return bottomCrudRef.value?.tableData || [];
});
const rowUpdate = (formSave, index, done) => {
  formSave.checker = bottomForm.value.checker;
  formSave.checkerName = bottomForm.value.checkerName;
  formSave.checkerCode = bottomForm.value.checkerCode;
  formSave.worker = bottomForm.value.worker;
  formSave.workerCode = bottomForm.value.workerCode;
  formSave.workerName = bottomForm.value.workerName;
  done(formSave);
};
const submitDialog = () => {
  topFormRef.value.validate((valid, done) => {
    if (valid) {
      dialog.value.loading = true;
      let tableData = [];
      getAllTableData(tableData, bottomCrudRef.value?.tableData);
      let schemaDTO = {};
      if (edit.value || clone.value) {
        schemaDTO.id = parentRow.value.id;
      }
      schemaDTO.name = topForm.value.name;
      schemaDTO.specificationId = topForm.value.specificationId;
      let notprocess = tableData.find((item) => {
            (!item.children || item.children.length == 0) && verifyNull(item.worker);
          }
      );
      if (verifyNotNull(notprocess)) {
        ElMessage.error(process.name + "工步的操作者不能为空！");
        dialog.value.loading = false;
        return false;
      }
      ;
      let itemDTOArr = tableData.map((item) => {
        return {
          id: edit.value ? item.id : null,
          code: item.code,
          name: item.name,
          processObjId: (item.processObjId || item.objId),
          worker: item.worker,
          workerCode: item.workerCode,
          workerName: item.workerName,
          checker: item.checker,
          checkerCode: item.checkerCode,
          checkerName: item.checkerName,
          fixedArmyFlag: (item.children || item.children.length == 0) ? ((item.fixedArmyFlag && item.fixedArmyFlag !== '') ? item.fixedArmyFlag : 'false') : "",
          orderNum: item.orderNum,
          parentId: item.parentId
        };
      });
      schemaDTO.itemDTOList = itemDTOArr;
      if (edit.value) {
        editAllotSchema(schemaDTO).then(res => {
          dialog.value.loading = false;
          ElMessage.success("编辑方案成功！");
          cancleDialog();
          emits("refresh-parent");
        }).catch(() => {
          // ElMessage.error("编辑方案失败！");
          done();
          dialog.value.loading = false;
        });
      } else if (clone.value) {
        //克隆
        cloneSchema(schemaDTO).then(() => {
          dialog.value.loading = false;
          ElMessage.success("克隆成功！");
          cancleDialog();
          emits("refresh-parent");
        }).catch(() => {
          // ElMessage.error("克隆失败！");
          done();
          dialog.value.loading = false;
        });
      } else {
        addAllotSchema(schemaDTO)
            .then((res) => {
              dialog.value.loading = false;
              ElMessage.success("添加方案成功！");
              cancleDialog();
              emits("refresh-parent");
            })
            .catch(() => {
              // ElMessage.error("添加方案失败！");
              done();
              dialog.value.loading = false;
            });
      }
    } else {
      return false;
    }
  })
};
defineExpose({
  openDialog
})


</script>

<style lang="scss" scoped>

</style>
